package cn.kk.utils;

import cn.kk.base.model.Payload;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.UUID;

public class JwtUtils {

    private static final String JWT_PAYLOAD_USER_KEY = "user";

    /**
     * 私钥加密token
     * @param info       载荷中的数据
     * @param privateKey 私钥
     * @param expire     过期时间，单位分钟
     * @return JWT
     */
    public static String generateTokenExpireInMinutes(Object info, PrivateKey privateKey, int expire) {
        return Jwts.builder()
                //claim: 往Jwt的载荷存入数据
                .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(info))
                //往Jwt的载荷存入数据，设置固定id的key
                .setId(createJTI())
                //往Jwt的载荷存入数据，设置固定exp的key
                .setExpiration(DateUtils.toDate(LocalDateTime.now().plusMinutes(expire)))
                //设置token的签名
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * 私钥加密token
     * @param info       载荷中的数据
     * @param privateKey 私钥
     * @param expire     过期时间，单位秒
     * @return JWT
     */
    public static String generateTokenExpireInSeconds(Object info, PrivateKey privateKey, int expire) {
        return Jwts.builder()
                .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(info))
                .setId(createJTI())
                .setExpiration(DateUtils.toDate(LocalDateTime.now().plusSeconds(expire)))
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * 公钥解析token
     * @param token     用户请求中的token
     * @param publicKey 公钥
     * @return Jws<Claims>
     */
    private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    /**
     * 生成JWT ID
     * @return ID
     */
    private static String createJTI() {
        return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
    }

    /**
     * 获取token中的用户信息
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     */
    public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        Payload<T> claims = new Payload<>();
        claims.setId(body.getId());
        claims.setInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
        claims.setExpiration(body.getExpiration());
        return claims;
    }

    /**
     * 获取token中的载荷信息
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     */
    public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        Payload<T> claims = new Payload<>();
        claims.setId(body.getId());
        claims.setExpiration(body.getExpiration());
        return claims;
    }

    public static void main(String[] args) {
        String token = "eyJhbGciOiJSUzI1NiJ9.eyJ1c2VyIjoie1widWlkXCI6bnVsbCxcInVzZXJOYW1lXCI6bnVsbCxcInBob25lXCI6bnVsbCxcImVtYWlsXCI6bnVsbCxcInNleFwiOm51bGwsXCJzdGF0ZVwiOm51bGx9IiwianRpIjoiTkRNek9HSXdOekl0WXpBNU9DMDBPREV4TFRsa01XSXROR1prTVRnNVptVmpaR1kwIiwiZXhwIjoxNjkxNDAxNTgyfQ.DxAy6ntekrOLORwhUWFFPbM-XSP_T0bSSH2liJbKByp-k4n_isR_9ibAT2dkYM50geGZUKCDWBJwsKW0bkDciBZc6XJ5bf5FEg1SA3icaPeeNsXpJokY0FFyPehS_cOe8Lvmia9EgtyTS22wHX4I2Z5j5WNhi6UrIwbzzB22iu2D3GTjKXUCxJU_3duH1WFHh9Vw1d6ruNmL7FIPMArwPD5LyIt11TF9ZXYFz80mLpN_5Q46Co9S6yWASM0lZiHrNZ10sElazuP8ojuVfUe5ujPhwzDvJPW22tVvY5v005R8vb44CiX-dKwrIUEungzZsO00B56oF6oCtzCgZgLyPQ";
    }
}